package com.wuliqing.android.zte.presenter;

import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.text.TextUtils;

import com.wuliqing.android.zte.calllog.CallLogQuery;
import com.wuliqing.android.zte.data.CallLogData;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 10172915 on 2015/7/7.
 */
public class LoadCallLogListPresenter {
    private Activity mActivity;
    private LoadContactDataListener mLoadContactDataListener;
    private List<CallLogData> mContactDataList;

    public LoadCallLogListPresenter(Activity activity, LoadContactDataListener listener, List<CallLogData> list) {
        mActivity = activity;
        mLoadContactDataListener = listener;
        mContactDataList = list;
    }

    public interface LoadContactDataListener {
        void requestContactData(List<CallLogData> list);
    }

    public void onStart() {
        mActivity.getLoaderManager().restartLoader(1, null, loaderCallbacks);
    }

    public void onDestroy() {
        mActivity.getLoaderManager().destroyLoader(1);
    }

    private final LoaderCallbacks<Cursor> loaderCallbacks = new LoaderCallbacks<Cursor>() {

        @Override
        public void onLoaderReset(Loader<Cursor> arg0) {

        }

        @Override
        public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
            cursor.moveToPosition(-1);
            mContactDataList.clear();
            while (cursor.moveToNext()) {
                if (cursor != null) {
                    CallLogData mContactData = new CallLogData();
                    final String number = cursor.getString(CallLogQuery.NUMBER);
                    final String name = cursor.getString(CallLogQuery.CACHED_NAME);
                    final long date = cursor.getLong(CallLogQuery.DATE);
                    if (TextUtils.isEmpty(name)) {
                        mContactData.setName(number);
                    } else {
                        mContactData.setName(name);
                    }
                    mContactData.setNumber(number);
                    mContactData.setTime(date);
                    mContactDataList.add(mContactData);
                }
            }

            if (null != mLoadContactDataListener) {
                mLoadContactDataListener.requestContactData(mContactDataList);
            }
        }

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            CursorLoader cursorLoader = new CursorLoader(mActivity);
            configCursorLoader(cursorLoader, -1, false, -1);//CallLog.Calls.MISSED_TYPE
            return cursorLoader;
        }

        private void configCursorLoader(CursorLoader cursorLoader,
                                        int callType, boolean newOnly, long newerThan) {
            Uri uri = CallLog.Calls.CONTENT_URI
                    .buildUpon()
                    .appendQueryParameter(CallLog.Calls.LIMIT_PARAM_KEY,
                            Integer.toString(1000)).build();

            StringBuilder where = new StringBuilder();
            ArrayList<String> selectionArgs = new ArrayList<String>();

            if (newOnly) {
                where.append(CallLog.Calls.NEW);
                where.append(" = 1");
            }

            if (callType > -1) {
                if (where.length() > 0) {
                    where.append(" AND ");
                }
                // Add a clause to fetch only items of type voicemail.
                where.append(String.format("(%s = ?)", CallLog.Calls.TYPE));
                // Add a clause to fetch only items newer than the requested
                // date
                selectionArgs.add(Integer.toString(callType));
            }

            if (newerThan > 0) {
                if (where.length() > 0) {
                    where.append(" AND ");
                }
                where.append(String.format("(%s > ?)", CallLog.Calls.DATE));
                selectionArgs.add(Long.toString(newerThan));
            }

            final String selection = where.length() > 0 ? where.toString()
                    : null;
            cursorLoader.setUri(uri);
            cursorLoader.setSelection(selection);
            cursorLoader.setSelectionArgs(selectionArgs.toArray(new String[0]));
            cursorLoader.setProjection(CallLogQuery._PROJECTION);
            cursorLoader.setSortOrder(CallLog.Calls.DEFAULT_SORT_ORDER);
        }
    };

}
